package com.huimin.merchant.service.impl;

import com.huimin.merchant.service.MerchantServiceApi;
import com.huimin.merchant.service.SmsService;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.PhoneUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


/**
 * @author amx
 * @create 2020/11/30 23:45
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

	@Autowired
	private RestTemplate restTemplate;

	@Value("${sms.url}")
	private String smsUrl;

	@Value("${sms.effectiveTime}")
	private String effectiveTime;

	@Reference
	private MerchantServiceApi merchantService;


	@Override
	public String getSmsCode(String mobile) {
		// 手机号空值判断
		if (StringUtils.isEmpty(mobile)) {
			throw new BusinessException(CommonErrorCode.E_200230);
		}
		// 手机号格式判断
		Boolean matches = PhoneUtil.isMatches(mobile);
		if (!matches) {
			throw new BusinessException(CommonErrorCode.E_200224);
		}
		//判断手机号是否注册过
		merchantService.findMerchantByPhone(mobile);

		// 声明请求体
		Map<String, String> body = new HashMap<>();
		body.put("mobile", "123456");
		// 请求头
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);

		HttpEntity httpEntity = new HttpEntity(body, httpHeaders);
		String url = smsUrl + "generate?name=sms&effectiveTime=" + effectiveTime;

		String key;
		try {
			ResponseEntity<Map> exchange = restTemplate.exchange(url,
			                                                     HttpMethod.POST,
			                                                     httpEntity,
			                                                     Map.class);
			Map exchangeBody = exchange.getBody();
			Map result = (Map) exchangeBody.get("result");
			key = result.get("key").toString();
			return key;
		} catch (Exception e) {
			// TODO: 2020/12/2  
			log.error("发送验证码失败！");
			return null;
		}


	}

	/**
	 * 检查验证码
	 *
	 * @param key     sms:key
	 * @param smsCode sms:code
	 */
	@Override
	public void checkSmsCode(String key, String smsCode) {
		// 空值判断
		if (StringUtils.isEmpty(key) || StringUtils.isEmpty(smsCode)) {
			// 日志记录
			log.error("发送验证码失败！参数为空");

			// 抛出自定义异常
			throw new BusinessException(CommonErrorCode.E_100103);

		}
		// 拼合实际访问url，进行smsCode的检验
		String url = smsUrl + "verify?name=sms&verificationCode="
				+ smsCode + "&verificationKey=" + key;

		// 使用restTemplate进行获取url的响应数据
		ResponseEntity<Map> entity = restTemplate.exchange(url,
		                                                   HttpMethod.POST,
		                                                   HttpEntity.EMPTY,
		                                                   Map.class);

		// 从响应数据里获取请求体
		Map body = entity.getBody();
		assert body != null;
		// 从请求体里获取"result"对应的value
		Boolean result = (Boolean) body.get("result");

		// 判断结果，若验证码错误则报错
		if (!result) {
			log.error("验证码错误！验证码为{}", smsCode);
			// throw new RuntimeException("验证码错误！");
			throw new BusinessException(CommonErrorCode.E_100102);
		}

	}

}
